/*
 * License GNU LGPL
 * Copyright (C) 2012 Amrullah <amrullah@panemu.com>.
 */
package com.abc.cheque.ui;


import java.util.Arrays;
import java.util.List;

import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.stage.Modality;
import javafx.stage.Stage;

import com.abc.cheque.common.TableCriteria;
import com.abc.cheque.common.TableData;
import com.abc.cheque.entity.Contact;
import com.abc.cheque.test.DaoBase;
import com.abc.cheque.test.TiwulfxDemo;
import com.abc.cheque.ui.dialog.MessageDialogBuilder;
import com.abc.cheque.ui.form.Form;
import com.abc.cheque.ui.table.TableController;

/**
 *
 * @author Amrullah <amrullah@panemu.com>
 */
public class InFormMaintenanceController extends TableController<Contact> {

    private DaoBase<Contact> daoPerson = new DaoBase<>(Contact.class);
    private Stage dialogStage;// = new Stage();
    private FrmPersonMaintenance frmPersonMaintenance;

    @Override
    public TableData loadData(int startIndex, List<TableCriteria> filteredColumns, List<String> sortedColumns, List<TableColumn.SortType> sortingOrders, int maxResult) {
        TableData result = daoPerson.fetch(startIndex, filteredColumns, sortedColumns, sortingOrders, maxResult, Arrays.asList(Person_.insurance.getName()));
        return result;
    }

    @Override
    public Contact preInsert(Contact newRecord) {
        showFrmPersonMaintenance(newRecord, Form.Mode.INSERT);
        return null;
    }

    @Override
    public boolean canEdit(Contact selectedRecod) {
        if (selectedRecod == Contact) {
            MessageDialogBuilder.error().message("Please select a record to edit.").show(null);
            return false;
        }
        showFrmPersonMaintenance(selectedRecod, Form.Mode.EDIT);
        return false;
    }

    @Override
    public void doubleClick(Contact record) {
        showFrmPersonMaintenance(record, Form.Mode.READ);
    }
    
    @Override
    public void delete(List<Contact> records) {
        daoPerson.delete(records);
    }

    private void showFrmPersonMaintenance(Contact person, Form.Mode mode) {
        if (dialogStage == null) {
            frmPersonMaintenance = new FrmPersonMaintenance();
            /**
             * cannot instantiate dialogStage when instantiating this class
             * because it's done in non-FX thread. It turns that instantiating
             * stage should be in FX thread..
             */
            dialogStage = new Stage();
            dialogStage.initOwner(TiwulfxDemo.mainStage);
            dialogStage.initModality(Modality.WINDOW_MODAL);
            dialogStage.setScene(new Scene(frmPersonMaintenance));
            dialogStage.getScene().getStylesheets().add("tiwulfx.css");
        }
        frmPersonMaintenance.setPerson(person);
        frmPersonMaintenance.setMode(mode);
        dialogStage.show();
    }
}
